//
//  AppleSignButton.swift
//  sdxf
//
//  Created by 湛亚磊 on 2020/2/7.
//  Copyright © 2020 湛亚磊. All rights reserved.
//

import UIKit
import AuthenticationServices
import RxSwift
import RxCocoa
open class AppleSignButton: UIButton {
    
    private var disposeBag = DisposeBag()
    /// id,name,email,status,token,authcode
    private var sucessCallBlock:((String,String,String,String,Data?,Data?)->Void)?
    private var failurCallBlock:((Error)->())?
    public override init(frame: CGRect) {
        super.init(frame: frame)
        setSubViews()
        
        self.rx.tap.subscribe(onNext: {[weak self] () in
            self?.appClick()
        }).disposed(by: disposeBag)
    }
    
    private func setSubViews()  {
        if #available(iOS 13.0, *) {
            let appleButton:ASAuthorizationAppleIDButton=ASAuthorizationAppleIDButton(type: .signIn, style: .whiteOutline)
            appleButton.isUserInteractionEnabled=false
            appleButton.largeContentTitle = ""
            appleButton.frame=CGRect(x: 0, y: 0, width: size.width, height: size.height)
            appleButton.cornerRadius=size.height/2
            self.addSubview(appleButton)
        }

    }
    private func appClick()  {
        ///苹果登录
        if #available(iOS 13.0,*){
            ToastView.instance.showLoadingView()
            //基于用户的Apple ID授权用户，生成用户授权请求的一种机制
            let provide=ASAuthorizationAppleIDProvider()
            //创建新的AppleID 授权请求
            let request:ASAuthorizationAppleIDRequest = provide.createRequest()
            //在用户授权期间请求的联系信息
            request.requestedScopes = [.fullName,.email]
            //由ASAuthorizationAppleIDProvider创建的授权请求 管理授权请求的控制器
            let controller:ASAuthorizationController=ASAuthorizationController(authorizationRequests: [request])
            //设置授权控制器通知授权请求的成功与失败的代理
            controller.delegate=self
            //设置提供 展示上下文的代理，在这个上下文中 系统可以展示授权界面给用户
            controller.presentationContextProvider = self
            controller.performRequests()
        }
    }
    
    /// 成功和失败的block
    public func postActionBlock(withSucess sucess:@escaping ((String,String,String,String,Data?,Data?)->Void),withFail fail:@escaping ((Error)->()))  {
        sucessCallBlock=sucess
        failurCallBlock=fail
    }
    
    
    public required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}
@available(iOS 13.0, *)
extension AppleSignButton:ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding{
    /// MARK: ASAuthorizationControllerDelegate
    //在授权成功回调中，我们可以拿到以下几类数据：
    //    User ID: Unique, stable, team-scoped user ID，苹果用户唯一标识符，该值在同一个开发者账号下的所有
    @available(iOS 13.0, *)
    public func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
            let userIdentifier = appleIDCredential.user
            let fullName = (appleIDCredential.fullName?.familyName ?? "") + (appleIDCredential.fullName?.givenName ?? "")
            
            let email = appleIDCredential.email ?? ""
            let realUserStatus = "\(appleIDCredential.realUserStatus.rawValue)"
            let identityToken = appleIDCredential.identityToken
            let authCode = appleIDCredential.authorizationCode
            ///拼接参数
            // Create account in your system
            sucessCallBlock?(userIdentifier,fullName,email,realUserStatus,identityToken,authCode)
            
        }
    }

    @available(iOS 13.0, *)
    public func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        ToastView.instance.clear()
        failurCallBlock?(error)
    }

    
    /// MARK: ASAuthorizationControllerPresentationContextProviding
    @available(iOS 13.0, *)
    public func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        return self.window!
    }
}



//// 使用示例 在 appDelegate中需要做apple登录检测
///检查苹果登录的状态
//private func checkAppleSign()  {
//    if #available(iOS 13.0, *) {
//        ///检测状态
//        let provider:ASAuthorizationAppleIDProvider = ASAuthorizationAppleIDProvider()
//        /// 拉取本地的app_id
//        let apple_user_id = UserManager.sharedInstance.get_apple_user_id()
//        if apple_user_id == ""{
//            ///正常的其他登录
//            return
//        }
//        ///苹果登录的处理
//        provider.getCredentialState(forUserID: apple_user_id) {[weak self] (state, error) in
//            switch state {
//            case .notFound:
//                //该userid apple id 登录找不到
//                //用户在设置-appleid header-密码与安全性-使用您 Apple ID的App 中将禁止掉了
//                self?.apple_sign_login_out() ///清掉记录 重新登录
//                break
//            case .revoked:
//                //用户重新登录了其他的apple id 登出+提示
//                self?.apple_sign_login_out() ///清掉记录 重新登录
//                break
//            case .authorized:
//                //该userid apple id 登录状态良好 继续用户行为即可
//                break
//            case .transferred:
//                //用户换了其他账号 登出+提示
//                self?.apple_sign_login_out() ///清掉记录 重新登录
//                break
//            @unknown default:
//                print("异常情况")
//            }
//        }
//    } else {
//        // Fallback on earlier versions
//    }
//}

